package cn.hj.config;

import javax.servlet.ServletContainerInitializer;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.HandlesTypes;
import java.lang.reflect.Modifier;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;

@HandlesTypes(WebInitializerInterface.class)
public class MyServletContainerInitializer implements ServletContainerInitializer {
    @Override
    public void onStartup(Set<Class<?>> set, ServletContext servletContext) throws ServletException {
        List<WebInitializerInterface> initializers = new LinkedList<>();

        if(set!=null){
            for (Class<?> clazz: set) {
                if(!clazz.isInterface() && !Modifier.isAbstract(clazz.getModifiers()) && WebInitializerInterface.class.isAssignableFrom(clazz)){
                    try {
                        initializers.add((WebInitializerInterface) clazz.newInstance()) ;
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        if (initializers.isEmpty()){
            servletContext.log("初始化类数量为0");
            return ;
        }
        servletContext.log("初始化类数量" + initializers.size());
        for (WebInitializerInterface c:
             initializers) {
            c.init(servletContext);
        }
    }
}
